package edu.swust.graduation_project.eauction.fragment

import android.app.Activity
import android.app.DatePickerDialog
import android.app.TimePickerDialog
import android.content.Intent
import android.content.SharedPreferences
import android.icu.util.Calendar
import android.net.Uri
import android.os.Bundle
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.annotation.Nullable
import androidx.appcompat.app.AppCompatActivity
import androidx.core.net.toUri
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.tencent.cos.xml.CosXmlService
import com.tencent.cos.xml.CosXmlServiceConfig
import com.tencent.cos.xml.exception.CosXmlClientException
import com.tencent.cos.xml.exception.CosXmlServiceException
import com.tencent.cos.xml.listener.CosXmlResultListener
import com.tencent.cos.xml.model.CosXmlRequest
import com.tencent.cos.xml.model.CosXmlResult
import com.tencent.cos.xml.transfer.COSXMLUploadTask
import com.tencent.cos.xml.transfer.TransferConfig
import com.tencent.cos.xml.transfer.TransferManager
import com.tencent.qcloud.core.auth.QCloudCredentialProvider
import com.tencent.qcloud.core.auth.ShortTimeCredentialProvider
import edu.swust.graduation_project.eauction.R
import edu.swust.graduation_project.eauction.activity.ContainerActivity
import java.sql.Connection
import java.sql.DriverManager
import java.sql.SQLException
import java.text.SimpleDateFormat
import java.util.*


class AddItemFragment : Fragment() {
    lateinit var uri: Uri
    var nowDate = SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date(System.currentTimeMillis()))


    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view: View = inflater.inflate(R.layout.fragment_additem, container, false)
        val mEtItemName = view.findViewById<EditText>(R.id.et_add_itemname)
        val mEtItemPrice = view.findViewById<EditText>(R.id.et_add_itemprice)
        val mEtItemEndTime = view.findViewById<TextView>(R.id.tv_add_item_endtime)
        val mBtnSetItemIcon = view.findViewById<Button>(R.id.btn_add_itemicon)
        val mBtnUpload = view.findViewById<Button>(R.id.btn_add_item)
        val calendar: Calendar = Calendar.getInstance(Locale.CHINA)


        mEtItemEndTime.setOnClickListener {
            showTimePickerDialog(0, mEtItemEndTime, calendar)
            showDatePickerDialog(0, mEtItemEndTime, calendar)
        }


        mBtnSetItemIcon.setOnClickListener {
            openAlbum()
        }


        mBtnUpload.setOnClickListener {
            if (mEtItemName.text.isEmpty() || mEtItemPrice.text.isEmpty() || mEtItemEndTime.text.isEmpty()) {
                Toast.makeText(activity, "请填写完整信息", Toast.LENGTH_SHORT).show()
            } else {
                if (this::uri.isInitialized) {
                    val mSharedPreferences: SharedPreferences =
                        requireContext().getSharedPreferences(
                            "user",
                            AppCompatActivity.MODE_PRIVATE
                        )
                    object : Thread() {
                        override fun run() {
                            super.run()
                            addItemMysql(
                                mEtItemName,
                                mEtItemPrice,
                                mSharedPreferences.getString("username", ""), nowDate,
                                mEtItemEndTime.text.toString()
                            )
                            Looper.prepare()
                            Toast.makeText(activity, "上传物品成功", Toast.LENGTH_SHORT).show()
                            fragmentManager?.beginTransaction()
                                ?.replace(R.id.fl_container, AddItemFragment())
                                ?.commitAllowingStateLoss()
                        }
                    }.start()
                } else {
                    Toast.makeText(activity, "请选择商品图片", Toast.LENGTH_SHORT).show()
                }
            }
        }
        return view
    }

    //日期选择器
    private fun showDatePickerDialog(
        themeResId: Int,
        tv: TextView,
        calendar: Calendar
    ) {
        // 直接创建一个DatePickerDialog对话框实例，并将它显示出来
        DatePickerDialog(
            requireActivity(),
            themeResId,
            { view, year, monthOfYear, dayOfMonth ->
                // 绑定监听器
                tv.text = "$year-" + (monthOfYear + 1).toString() + "-$dayOfMonth"
            } // 设置初始日期
            ,
            calendar.get(Calendar.YEAR),
            calendar.get(Calendar.MONTH),
            calendar.get(Calendar.DAY_OF_MONTH)).show()
    }

    //时间选择器
    private fun showTimePickerDialog(
        themeResId: Int,
        tv: TextView,
        calendar: Calendar
    ) {
        //创建TimePickerDialog并显示
        TimePickerDialog(requireActivity(), themeResId,  // 绑定监听器
            { view, hourOfDay, minute ->
                tv.text = tv.text.toString() + " $hourOfDay:$minute:00"
                if (Date(System.currentTimeMillis())
                        .after
                            (SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(tv.text.toString()))
                ) {
                    tv.text = null
                    Toast.makeText(activity, "选择时间应提前于当前时间", Toast.LENGTH_SHORT).show()
                }
            } // 设置初始时间
            , calendar[Calendar.HOUR_OF_DAY], calendar[Calendar.MINUTE] // true表示采用24小时制
            , true).show()
    }


    private fun uploadCOS(uri: Uri) {
        val secretId = "*" //永久密钥 secretId
        val secretKey = "*" //永久密钥 secretKey
        // keyDuration 为请求中的密钥有效期，单位为秒
        val myCredentialProvider: QCloudCredentialProvider =
            ShortTimeCredentialProvider(secretId, secretKey, 300)
        // 存储桶所在地域简称，例如广州地区是 ap-guangzhou
        val region = "ap-chengdu"
        // 创建 CosXmlServiceConfig 对象，根据需要修改默认的配置参数
        val serviceConfig = CosXmlServiceConfig.Builder()
            .setRegion(region)
            .isHttps(true) // 使用 HTTPS 请求, 默认为 HTTP 请求
            .builder()
        // 初始化 COS Service，获取实例
        val cosXmlService: CosXmlService = CosXmlService(
            context,
            serviceConfig, myCredentialProvider
        )
        // 初始化 TransferConfig，这里使用默认配置，如果需要定制，请参考 SDK 接口文档
        val transferConfig = TransferConfig.Builder().build()
        // 初始化 TransferManager
        val transferManager = TransferManager(
            cosXmlService,
            transferConfig
        )
        // 存储桶名称，由bucketname-appid 组成，appid必须填入
        val bucket = "*"
        val cosPath = "*" +
                nowDate +
                ".png" //对象在存储桶中的位置标识符，即称对象键
        //本地文件的绝对路径
        val srcPath: Uri = uri
        //若存在初始化分块上传的 UploadId，则赋值对应的 uploadId 值用于续传；否则，赋值 null
        var uploadId: String? = null
        // 上传文件
        val cosxmlUploadTask = transferManager.upload(
            bucket, cosPath,
            srcPath, uploadId
        )

        //上传结果回调
        cosxmlUploadTask.setCosXmlResultListener(object : CosXmlResultListener {
            override fun onSuccess(request: CosXmlRequest, result: CosXmlResult) {
                result as COSXMLUploadTask.COSXMLUploadTaskResult
                Log.d("COS", "上传成功")
            }


            // 如果您使用 kotlin 语言来调用，请注意回调方法中的异常是可空的，否则不会回调 onFail 方法，即：
            // clientException 的类型为 CosXmlClientException?，serviceException 的类型为 CosXmlServiceException?
            override fun onFail(
                request: CosXmlRequest,
                @Nullable clientException: CosXmlClientException?,
                @Nullable serviceException: CosXmlServiceException?
            ) {
                if (clientException != null) {
                    clientException.printStackTrace()
                } else {
                    serviceException!!.printStackTrace()
                }
            }
        })
    }


    private fun openAlbum() {
        val intent = Intent()
        intent.type = "image/*"
        intent.action = "android.intent.action.GET_CONTENT"
        intent.addCategory("android.intent.category.OPENABLE")
        startActivityForResult(intent, 1)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                1 -> run {
                    data?.dataString?.let { Log.d("URL", it) }
                    uri = data?.data!!
                    val mIvAddItemIcon = view?.findViewById<ImageView>(R.id.iv_add_item_icon)
                    Glide.with(requireActivity()).load(data?.data)
                        .skipMemoryCache(true)
                        .diskCacheStrategy(DiskCacheStrategy.NONE)
                        .into(mIvAddItemIcon!!)
                }
            }
        }
    }


    private fun addItemMysql(
        itemName: EditText,
        itemPrice: EditText,
        itemCreateUser: String?,
        itemCreateTime: String,
        itemEndTime: String
    ) {
        val itemName = itemName.text.toString().trim()
        val itemPrice = itemPrice.text.toString().trim()
        val sqlInsert =
            "INSERT INTO `test_case`.`Item` (`item_name`, `item_create_time`, `item_price`, `item_create_user`, `item_end_time`, `item_last_bid`, `item_starting_price`) VALUES " +
                    "('$itemName', '$itemCreateTime', '$itemPrice', '$itemCreateUser', '$itemEndTime', '$itemCreateUser', '$itemPrice')"
        val cn: Connection
        try {
            //建立连接
            cn = DriverManager.getConnection(
                "*e",
                "*", "*"
            )
            val ps = cn.createStatement()
            ps.execute(sqlInsert)
            ps.close()
            cn?.close()
            uploadCOS(uri)
        } catch (e: ClassNotFoundException) {
            e.printStackTrace()
        } catch (e: SQLException) {
            e.printStackTrace()
        }
    }
}